<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class UserLogoutHs extends Model
{
    protected $table = 'userlogouthslog';
    protected $default_table_name = 'userlogouthslog';
    private static $suffix;
    public $timestamps = false;

    public function __construct($suffix = null)
    {
        $this->setConnection('mysql_userlog');
        if (!$suffix) {
            $suffix = date('Ym');
        }
        $this->table = $this->default_table_name . $suffix;
        parent::__construct();
    }

    public function setTable($suffix)
    {
        $table = $this->default_table_name . $suffix;
        if (!Schema::hasTable($table)) {
            $table = $this->default_table_name . date('Ym');
        }

        return $this->table = $table;
    }

    public function getOnlineTimes($date, $server)
    {
        $this->setTable(date('Ym', $date));
        $res = [];
        $online_data = $this->select(DB::raw('max(onlinetime) as max_onlinetime, userid'))
            ->where('receivetime', 'like', date('Ymd', $date) . '%')
            ->where('servername', $server)
            ->groupBy('userid')
            ->get()->toArray();
        foreach ($online_data as $value) {
            $type = $this->typeOnlineTime($value['max_onlinetime']);
            isset($res[$type]) ? $res[$type]++ : ($res[$type]=0);
        }

        return $res;
    }

    public function typeOnlineTime($time)
    {
        $type = '';
        switch ($time) {
            case $time <= 10:
                $type = '<=10';
                break;
            case $time > 10 && $time <= 60:
                $type = '<=60';
                break;
            case $time > 60 && $time <= 240:
                $type = '<=240';
                break;
            case $time > 240 && $time <= 360:
                $type = '<=360';
                break;
            case $time > 360 && $time <= 720:
                $type = '<=720';
                break;
            case $time > 720:
                $type = '>720';
                break;
        }
        return $type;
    }
}
